package com.rdc.qingkou.model;


import android.widget.Toast;

import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.config.URL;
import com.rdc.qingkou.dto.CommentDTO;
import com.rdc.qingkou.dto.ResultDTO;
import com.rdc.qingkou.entity.User;
import com.rdc.qingkou.model.imodel.IOneLevelCommentModel;
import com.rdc.qingkou.presenter.OneLevelCommentPresenter;
import com.rdc.qingkou.retrofitService.ICommentService;
import com.rdc.qingkou.utils.MyUtils;
import com.rdc.qingkou.vo.CommentOneLevelVO;
import com.rdc.qingkou.vo.UserVO;

import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Response;

public class OneLevelCommentModel implements IOneLevelCommentModel {

    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    private OneLevelCommentPresenter presenter;
    private List<CommentOneLevelVO> hotComments;
    private List<CommentOneLevelVO> recentComments;
    private String errorMessage;

    public OneLevelCommentModel(OneLevelCommentPresenter presenter) {
        this.presenter = presenter;
    }


    @Override
    public void clearDisposable() {
        mCompositeDisposable.dispose();
    }

    @Override
    public void addDisposable(Disposable disposable) {
        mCompositeDisposable.add(disposable);
    }


    @Override
    public void appreciate(final int commentId) {
        MyUtils.getRetrofitProvider(URL.GET_APPRECIATE_COMMENT)
                .create(ICommentService.class)
                .appreciate(commentId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<ResultDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<ResultDTO> resultDTOResponse) {
                        if (resultDTOResponse.code() != HttpURLConnection.HTTP_OK) {
                            presenter.appreciateError("点赞/取消点赞失败！error code " + resultDTOResponse.code());
                        } else if (resultDTOResponse.body().isSuccess()) {
                            presenter.appreciateSuccess(commentId, resultDTOResponse.body().getMessage());
                        } else {
                            presenter.appreciateError("点赞/取消点赞失败！" + resultDTOResponse.code());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof SocketTimeoutException) {
                            Toast.makeText(MyApplication.getContext(), "SocketTimeOut !", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void sendOneLevelComment(final String input, final Integer cardId, Integer userId) {
        MyUtils.getRetrofitProvider(URL.POST_SEND_ONE_LEVEL_COMMENT).create(ICommentService.class)
                .sendOneLevelComment(cardId, userId, input)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Response<ResultDTO>>() {
                    @Override
                    public void accept(Response<ResultDTO> response) throws Exception {
                        if (response.code() != HttpURLConnection.HTTP_OK) {
                            presenter.sendOneLevelCommentError("发送评论失败! error code:" + response.code());
                        } else if (!response.body().isSuccess()) {
                            presenter.sendOneLevelCommentError("发送评论失败! 原因:" + response.body().getReason());
                        } else {
                            CommentOneLevelVO c = new CommentOneLevelVO();
                            c.setPraiseNumber(0);
                            c.setPraise(false);
                            c.setContent(input);
                            c.setCardId(cardId);
                            UserVO userVO = new UserVO();
                            User user = MyApplication.getUser();
                            userVO.setUserId(user.getUserId());
                            userVO.setNickName(user.getNickName());
                            if (user.getImageUrl() == null) {
                                userVO.setHeadImageUrl(MyUtils.getUriFromDrawableRes(MyApplication.getContext(), R.drawable.pic6));
                            } else {
                                userVO.setHeadImageUrl(user.getImageUrl());
                            }
                            c.setUser(userVO);
                            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            c.setCommentDate(dateFormatter.format(new Date()));
                            c.setCommentsNumber(0);
                            c.setCommentId(0);
                            presenter.sendOneLevelCommentSuccess(c);
                        }
                    }
                });
    }

    @Override
    public void getOneLevelComment(final int cardId, final int currentPage) {
        MyUtils.getRetrofitProvider(URL.GET_ONE_LEVEL_HOT_COMMENT).create(ICommentService.class)
                .getOneLevelHotComment(cardId)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .flatMap(new Function<Response<CommentDTO>, Observable<Response<CommentDTO>>>() {
                    @Override
                    public Observable<Response<CommentDTO>> apply(@NonNull Response<CommentDTO> response) throws Exception {
                        //热门评论
                        if (response.code() != HttpURLConnection.HTTP_OK) {
                            errorMessage = "获取热门评论失败！error code:" + response.code();
                            return Observable.error(new Throwable("获取评论失败！"));
                        }
                        hotComments = response.body().transformToOneLevel();
                        return MyUtils.getRetrofitProvider(URL.GET_ONE_LEVEL_RECENT_COMMENT)
                                .create(ICommentService.class)
                                .getOneLevelRecentComment(cardId, currentPage);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<CommentDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<CommentDTO> response) {
                        //最新评论
                        if (response.code() != HttpURLConnection.HTTP_OK) {
                            presenter.getOneLevelCommentError("获取评论失败！error code:" + response.code());
                            return;
                        }
                        recentComments = response.body().transformToOneLevel();
                        presenter.getOneLevelCommentSuccess(hotComments, recentComments);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e.getMessage().equals("获取评论失败！")) {
                            presenter.getOneLevelCommentError(errorMessage);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    @Override
    public void loadMoreOneLevelComment(int cardId, int currentPage) {
        MyUtils.getRetrofitProvider(URL.GET_ONE_LEVEL_RECENT_COMMENT).create(ICommentService.class)
                .getOneLevelRecentComment(cardId, currentPage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Response<CommentDTO>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(Response<CommentDTO> listResponse) {
                        //最新评论
                        if (listResponse.code() != HttpURLConnection.HTTP_OK) {
                            presenter.loadMoreOnrLevelCommentError("获取评论失败！error code:" + listResponse.code());
                            return;
                        }
                        recentComments = listResponse.body().transformToOneLevel();
                        presenter.loadMoreOneLevelCommentSuccess(recentComments);
                    }

                    @Override
                    public void onError(Throwable e) {
                        presenter.loadMoreOnrLevelCommentError(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
